<?php


namespace app\common\business;
use app\common\lib\Str;
use app\common\lib\Time;
use app\common\model\mysql\User as UserModel;
use think\Exception;


class User
{
    public $userObj = null;
    public function __construct()
    {
        $this->userObj = new UserModel();
    }
    public function login($data){
       $redisCode =  cache(config('redis.code_pre').$data['phone_number']);
       if(empty($redisCode) || $redisCode != $data['code']){
           throw  new \think\Exception("不存在该验证码");
       }
       // 需要普安段是否 有记录，
        // 生成token
        $user = $this->userObj->getUserByPhoneNumber($data['phone_number']);

       if(!$user){
            $username = '商城用户'.$data['phone_number'];
            $userData = [
                'username' => $username,
                'phone_number' => $data['phone_number'],
                'type' => $data['type'],
                'status' => config('status.mysql.table_normal')
            ];
            $this->userObj->save($userData);
            $userId = $this->userObj->id;
       }else{
               $userId = $user->id;
               $username = $user->username;
       }

       $token = Str::getLoginToken($data['phone_number']);
       $redisData = [
           'id' => $userId,
           'username' => $username
       ];
       $res = cache(config('redis.token_pre').$token,$redisData,Time::userLoginExpiresTime($data['type']));

       return  $res ? ['token' => $token,"username"=>$username] : false;
    }
    public function getNormalUserById($id){
        $user = $this->userObj->getUserById($id);
        if(!$user || $user->status != config("status.mysql.table_normal")){
            return [];
        }
        return $user->toArray();
    }
    public function getNormalUserByUsername($Username){
        $user = $this->userObj->getUserByUsername($Username);
        if(!$user || $user->status != config("status.mysql.table_normal")){
            return [];
        }
        return $user->toArray();
    }
    public function update($id,$data){
        $userResult = $this->getNormalUserByUsername($data['username']);
        if($userResult && $userResult['id'] != $id){
            throw  new \think\Exception("用户名");
        }
        return  $this->userObj->updateById($id,$data);
    }
}